package com.appsys.controller;

import com.appsys.pojo.*;
import com.appsys.service.AppInfoService;
import com.appsys.service.DevService;
import com.appsys.service.VersionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName VersionController
 * @Description TODO
 * @Author YinLiangTao Email:1517535831@qq.com
 * @Date 2022/3/3 19:32
 * @Version 1.0
 */
@Controller
public class VersionController {
    @Resource
    private VersionService versionService;

    @Resource
    private AppInfoService appInfoService;

    @Resource
    private DevService devService;

    //跳转新增版本信息页
    @RequestMapping(value = "/toAddVersion/{devId}/{id}")
    public String toAddVersion(@PathVariable(value = "devId")int devId, @PathVariable(value = "id")int id, Model model){
        List<Version> versions = versionService.getVersionByAppId(id);
        Map<Object, Object> map = new HashMap<>();
        map.put("devId",devId);
        map.put("id",id);
        Dev dev = devService.getDevById(devId);
        model.addAttribute("devName",dev.getDevName());
        List<AppInfo> appInfoByDevId = appInfoService.getAppInfoByDevId(map);
        String softwareName = appInfoByDevId.get(0).getSoftwareName();
        String apkName = appInfoByDevId.get(0).getApkName();
        model.addAttribute("softwareName",softwareName);
        model.addAttribute("versions",versions);
        model.addAttribute("devId",devId);
        model.addAttribute("id",id);
        model.addAttribute("apkName",apkName);
        return "addVersion";
    }

    //跳转修改版本信息页
    @RequestMapping(value = "/toModifyVersion/{devId}/{id}/{versionId}")
    public String toModifyVersion(@PathVariable(value = "devId")int devId, @PathVariable(value = "id")int id, @PathVariable(value = "versionId")int versionId,Model model){
        List<Version> versions = versionService.getVersionByAppId(id);
        Version versionById = versionService.getVersionById(versionId);
        Map<Object, Object> map = new HashMap<>();
        map.put("devId",devId);
        map.put("id",id);
        Dev dev = devService.getDevById(devId);
        model.addAttribute("devName",dev.getDevName());
        List<AppInfo> appInfoByDevId = appInfoService.getAppInfoByDevId(map);
        String softwareName = appInfoByDevId.get(0).getSoftwareName();
        String apkName = appInfoByDevId.get(0).getApkName();
        model.addAttribute("softwareName",softwareName);
        model.addAttribute("versions",versions);
        model.addAttribute("versionById",versionById);
        model.addAttribute("devId",devId);
        model.addAttribute("id",id);
        model.addAttribute("versionId",versionId);
        model.addAttribute("apkName",apkName);
        String apkLocPath = versionById.getApkLocPath();
        if(apkLocPath != null){
            model.addAttribute("apkLocPath",apkLocPath);
            model.addAttribute("downloadApkLocPath","static/apkfiles/" + apkLocPath );
        }
        return "modifyVersion";
    }

    //增加版本信息
    @RequestMapping(value = "version/{devId}/{id}",method = RequestMethod.POST)
    public String addVersion(@PathVariable(value = "devId")int devId,
                             @PathVariable(value = "id")int id,
                             @RequestParam(value = "apkLocPath") MultipartFile apkLocPath,
                             @RequestParam(value = "versionNo") String versionNo,
                             @RequestParam(value = "apkName") String apkName,
                             @RequestParam(value = "versionSize") double versionSize,
                             @RequestParam(value = "publishstatus") String publishstatus,
                             @RequestParam(value = "versionInfo") String versionInfo,
                             HttpServletRequest request, Model model) {
        String idPicPath = null;
        //判断文件是否为空
        if(!apkLocPath.isEmpty()){
            //要保存的上传的路径
            String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "apkfiles");
            String oldFileName = apkLocPath.getOriginalFilename();//源文件名
            String prefix = oldFileName.substring(oldFileName.lastIndexOf(".")+1,oldFileName.length());//获取后缀名
            int filesize = 500000000;
            if(apkLocPath.getSize() > filesize){//上传文件不大于500MB
                request.setAttribute("uploadFileError","*上传文件不得大于500MB");
                return "forward:/toAddVersion/" + devId + "/" + id;
            }else if(prefix.equalsIgnoreCase("apk"))
            {
                String fileName = apkName + "-" + versionNo + ".apk";
                //在指定条件下创建一个文件
                File file = new File(path, fileName);
                if(!file.exists()){
                    file.mkdirs();
                }
                ////将文件保存到服务器指定位置
                try {
                    apkLocPath.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError","*上传失败");
                    return "forward:/toAddVersion/" + devId + "/" + id;
                }
                idPicPath = fileName;
            }else {
                request.setAttribute("uploadFileError","*上传图片格式不正确");
                return "forward:/toAddVersion/" + devId + "/" + id;
            }
        }
        Version version = new Version();
        version.setVersionNo(versionNo);
        version.setVersionSize(versionSize);
        version.setVersionInfo(versionInfo);
        version.setApkLocPath(idPicPath);
        version.setDownloadLink("http://www.dlka.com");
        version.setAppId(id);
        version.setModifyDate(new Date());
        version.setPublishStatus(new PublishStatus(3,"预发布"));
        boolean b = versionService.addVersion(version);
        List<Version> versionByAppId = versionService.getVersionByAppId(id);
        System.out.println(versionByAppId.get(0));
        if(appInfoService.updateInfoByVersion(versionByAppId.get(0))){
            return "redirect:/list/" + devId + "/1?flag=1";
        }
        return "forward:/toAddVersion/" + devId + "/" + id;
    }

    //更新版本信息
    @RequestMapping(value = "version/{devId}/{id}/{versionId}")
    public String updateVersion(@PathVariable(value = "devId")int devId,
                             @PathVariable(value = "id")int id,
                                @PathVariable(value = "versionId")int versionId,
                             @RequestParam(value = "apkLocPath",required = false) MultipartFile apkLocPath,
                             @RequestParam(value = "AlreadApkLocPath",required = false) String AlreadApkLocPath,
                             @RequestParam(value = "versionNo") String versionNo,
                             @RequestParam(value = "apkName") String apkName,
                             @RequestParam(value = "versionSize") double versionSize,
                             @RequestParam(value = "publishstatus",required = false) String publishstatus,
                             @RequestParam(value = "versionInfo") String versionInfo,
                             HttpServletRequest request, Model model) {
        String idPicPath = null;
        //判断文件是否为空
        if(!apkLocPath.isEmpty()){
            //要保存的上传的路径
            String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "apkfiles");
            String oldFileName = apkLocPath.getOriginalFilename();//源文件名
            String prefix = oldFileName.substring(oldFileName.lastIndexOf(".")+1,oldFileName.length());//获取后缀名
            int filesize = 500000000;
            if(apkLocPath.getSize() > filesize){//上传文件不大于500MB
                request.setAttribute("uploadFileError","*上传文件不得大于500MB");
                return "forward:/toModifyVersion/" + devId + "/" + id + "/" + versionId;
            }else if(prefix.equalsIgnoreCase("apk"))
            {
                String fileName = apkName + "-" + versionNo + ".apk";
                //在指定条件下创建一个文件
                File file = new File(path, fileName);
                if(!file.exists()){
                    file.mkdirs();
                }
                ////将文件保存到服务器指定位置
                try {
                    apkLocPath.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError","*上传失败");
                    return "forward:/toModifyVersion/" + devId + "/" + id + "/" + versionId;
                }
                idPicPath = fileName;
            }else {
                request.setAttribute("uploadFileError","*上传图片格式不正确");
                return "forward:/toModifyVersion/" + devId + "/" + id + "/" + versionId;
            }
        }
        Version version = new Version();
        version.setVersionNo(versionNo);
        version.setVersionSize(versionSize);
        version.setVersionInfo(versionInfo);
        if(idPicPath == null){
            version.setApkLocPath(AlreadApkLocPath);
        }else {
            version.setApkLocPath(idPicPath);
        }
        version.setModifyDate(new Date());
        version.setId(versionId);
        if(versionService.updateVersion(version)){
            return "redirect:/list/" + devId + "/1?flag=1";
        }
        return "forward:/toModifyVersion/" + devId + "/" + id + "/" + versionId;
    }
}
